<?php
declare (strict_types = 1);

namespace app\adminapi\controller;

use app\admin\model\SpecGoods;
use app\adminapi\validate\CheckBrand;
use app\common\model\Brand;
use app\common\model\GoodsImages;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class Goods
{
    /**
     * 商品列表
     * @return \think\response\Json
     */
    public function index()
    {

        try {
            //商品名称
            $goodsName=\request()->get('goods_name');
            $where=[];
            if($goodsName){
                $goodsName=trim($goodsName);
                $where[]=['goods_name','like',"%$goodsName%"];
            }
            //价格区间
            $min_price=\request()->get('min_price');
            $max_price=\request()->get('max_price');
            if($min_price && !$max_price){
                $where[]=['goods_price','>=',$min_price];
            }
            if(!$min_price && $max_price){
                $where[]=['goods_price','<=',$max_price];
            }
            if($min_price && $max_price && $min_price<$max_price){
                $where[]=['goods_price','between',[$min_price,$max_price]];
            }
            //商品分类
            $cate_id=\request()->get('cate_id');
            if($cate_id){
                $cate_id=trim($cate_id);
                if(!is_numeric($cate_id)){
                    return fail('cate_id参数格式错误');
                }
                $where[]=['cate_id','=',$cate_id];
            }
            $data=\app\common\model\Goods::field('cate_name')//一定要加这个field，否则后面关联了也出不来字段
            ->hasWhere('cate',function($query){
                $query->column('cate_name');
            })
                ->where($where)
                ->paginate(3);
            return successes('查询成功',$data);
        }catch (DbException $e){
            return fail($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //接收数据

        $files = $request->file('goods_images');
        //dd($files);
        if (!$files) {
            return fail('文件不存在');
        }
        //验证数据 ……
        $data = [
            'goods_name' => 'iphone X',
            'goods_price' => '8900',
            'goods_introduce' => 'iphone iphonex',
            'goods_logo' => '/uploads/goods/20190101/afdngrijskfsfa.jpg',
            'goods_images' => $files,
            'cate_id' => '72',
            'brand_id' => '3',
            'type_id' => '16',
            'item' => [
                '18_21' => [
                    'value_ids' => '18_21',
                    'value_names' => '颜色：黑色；内存：64G',
                    'price' => '8900.00',
                    'cost_price' => '5000.00',
                    'store_count' => 100
                ],
                '18_22' => [
                    'value_ids' => '18_22',
                    'value_names' => '颜色：黑色；内存：128G',
                    'price' => '9000.00',
                    'cost_price' => '5000.00',
                    'store_count' => 50
                ]
            ],
            'attr' => [
                '7' => ['id' => '7', 'attr_name' => '毛重', 'attr_value' => '150g'],
                '8' => ['id' => '8', 'attr_name' => '产地', 'attr_value' => '国产'],
            ]
        ];
        return \app\common\business\Type::Add($data);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
        if(!is_numeric($id)){
            return fail('参数格式不正确');
        }
        return \app\common\business\Type::GoodsEdit($id);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
        if(!is_numeric($id)){
            return fail('参数格式不正确');
        }
        $data=$request->all();
        $files=$request->file('goods_images');
        $data = [
            'goods_name' => '的副驾驶',
            'goods_price' => '8900',
            'goods_introduce' => 'iphone iphonex',
            'goods_logo' => '/uploads/goods/20190101/afdngrijskfsfa.jpg',
            'cate_id' => '72',
            'brand_id' => '3',
            'type_id' => '16',
            'item' => [
                '18_21' => [
                    'id'=>'885',
                    'value_ids' => '18_21',
                    'value_names' => '颜色：虹色；内存：64G',
                    'price' => '8900.00',
                    'cost_price' => '5000.00',
                    'store_count' => 100
                ],
                '18_22' => [
                    'id'=>'886',
                    'value_ids' => '18_22',
                    'value_names' => '颜色：黑色；内存：128G',
                    'price' => '9000.00',
                    'cost_price' => '5000.00',
                    'store_count' => 50
                ]
            ],
            'attr' => [
                '7' => ['id' => '7', 'attr_name' => '毛重', 'attr_value' => '200g'],
                '8' => ['id' => '8', 'attr_name' => '产地', 'attr_value' => '进口'],
            ]
        ];
        $files?$data['goods_images'] =$files:null;
        //参数验证，用中间件
        return \app\common\business\Type::GoodsUpdate($id,$data);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        if(!is_numeric($id)){
            return fail('参数格式不正确');
        }
        return \app\common\business\Type::GoodsDel($id);
    }


    //多图片上传
    public function add_pic(Request $request){

            $data=$request->all();
            $files= request()->file('image');
           foreach ($files as $file){//多文件上传写在循环里
               //验证文件大小和类型
               try {
               validate(['image'=>[
                   'fileExt'=>'jpg,jpeg,gif,png',
                   'fileSize'=>'2097152'
               ]])->check(['image'=>$file]);
               //dd($file);
               $savename = \think\facade\Filesystem::disk('public')->putFile($data['type'], $file);
               $success[]='storage/'.$savename;
               $error[]='';
               }catch (ValidateException $e){
                  $error[]=['name'=>$file->getOriginalName(),'msg'=>$e->getMessage()];
               }
           }

        return successes('上传成功',['success'=>$success,'error'=>$error]);
           //这里有个bug,error必须有错的才行，没有就报错,解决办法，在成功的try里写error，否则不走失败，error未定义


    }


    //单文件上传
    public function addPic(Request $request){
        try {
            $data=$request->all();
            $file = request()->file('image');
            //验证文件大小和类型
            validate(['image'=>[
                'fileExt'=>'jpg,jpeg,gif,png',
                'fileSize'=>'2097152'
            ]])->check($data);
            //dd($file);
            $savename = \think\facade\Filesystem::disk('public')->putFile( $data['type'], $file);
            // dd($savename);
            return successes('上传成功',['src'=>'storage/'.$savename]);
        }catch (ValidateException $e){
            return fail($e->getMessage());
        }

    }

    //商品品牌列表展示
    public function brand_show(){
        $page=\request()->get('page')??1;
        $size=\request()->get('size')??3;

        $data=Brand::paginate([
            'list_rows'=> $size,
            'page'=>$page
        ]);
       return successes('查询成功',$data);
    }

    //品牌数据的添加
    public function brand_add(Request $request){
        $data=$request->all();
        try {
            validate(CheckBrand::Class)->check($data);
            //dd($data);
            //文件上传,并进行缩略
            $image = \think\Image::open($data['logo']);
            $savename = \think\facade\Filesystem::disk('public')->putFile("brand", $data['logo']);
            $image->thumb(80, 80)->save('storage/'.$savename);
            $data['logo']='storage/'.$savename;
            Brand::create($data);
            return successes('添加成功');
        }catch (ValidateException $e){
            return fail($e->getMessage());
        }

    }
    //品牌数据的删除
    public function brand_del(Request $request){
        //获取品牌id
        $id=$request->get('id');
        //只能删除品牌下没有商品的品牌数据
        //联查出所有品牌下有商品的品牌id
        //只要商品id在这些数据中，就不能删除
        $list = \app\common\model\Goods::with('brands')->field('id,brand_id')->where('brand_id',$id)->paginate(3)->toArray();

       if($list['data']==[]){
            Brand::destroy($id);
            return successes('删除成功');
        }else{
            return fail('品牌下有商品，不能删除');
        }



    }

    //品牌数据的修改
    public function brand_edit(Request $request){
        try {
            //获取数据
            $data=$request->all();
            //dd($data);
            Brand::where('id', $data['id'])->save($data);
            return successes('修改成功');
        }catch (ModelNotFoundException $e){
            return fail($e->getMessage());
        }

    }
}
